<?php

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Paginator;
use think\Request;
use think\Validate;

class OrderRefund extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 查询退款记录是否存在
     * @return mixed
     */
    public function get_is_exist(){
        $oid = input('id');
        if(!$oid){
            return 'error';
        }
        $is_exist = Db::name('order_refund')->where('oid',$oid)->find();
        if($is_exist){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $data = input();
        $searchData = [];
        $url = '/admin/order_refund/index_html';
        if ($data) {
            foreach ($data as $dk => $dv) {
                if ($dk == $url) {
                    unset($data[$dk]);
                }
                if (!empty($dv)) {
                    $searchData[$dk] = $dv;
                }
            }
            $searchData['search'] = 'all';
        } else {
            $searchData['search'] = 'all';
        }

        if ($data['oid']) {
            $map['oid'] =  array('like', "%{$data['oid']}%");
        }
        if ($data['booking_people_name']) {
            $name_map['booking_people_name'] =  array('like', "%{$data['booking_people_name']}%");
            $name_ids = Db::name('order')->where('isrefund',1)->where($name_map)->field('id')->select();
            $name_id = '';
            if(count($name_ids)>0){
                foreach ($name_ids as $nk => $nv){
                    $name_id .= $nv['id'].',';
                }
                $name_id = rtrim($name_id,',');
            }
            $map['oid'] = array('in',$name_id);
        }
        if ($data['booking_people_phone']) {
            $phone_map['booking_people_phone'] =  array('like', "%{$data['booking_people_phone']}%");
            $phone_ids = Db::name('order')->where('isrefund',1)->where($phone_map)->field('id')->select();
            $phone_id = '';
            if(count($phone_ids)>0){
                foreach ($phone_ids as $pk => $pv){
                    $phone_id .= $pv['id'].',';
                }
                if($map['oid']){
                    $phone_id = $phone_id.$map['oid'];
                }else{
                    $phone_id = rtrim($phone_id,',');
                }
            }
            $map['oid'] = array('in',$phone_id);
        }
        if ($data['refund_type']) {
            $map['refund_type'] = $data['refund_type'];
        }
        if ($data['create_time_start'] && $data['create_time_end']) {
            if($data['create_time_start']>$data['create_time_end']){
                $map['create_time'] = array("between", [strtotime($data['create_time_end'] . " 00:00:00"), strtotime($data['create_time_start'] . " 23:59:59")]);
            }else{
                $map['create_time'] = array("between", [strtotime($data['create_time_start'] . " 00:00:00"), strtotime($data['create_time_end'] . " 23:59:59")]);
            }
        } else {
            if ($data['create_time_start']) {
                $map['create_time'] = array("between", [strtotime($data['create_time_start'] . " 00:00:00"), strtotime($data['create_time_start'] . " 23:59:59")]);
            }
            if ($data['create_time_end']) {
                $map['create_time'] = array("between", [strtotime($data['create_time_end'] . " 00:00:00"), strtotime($data['create_time_end'] . " 23:59:59")]);
            }
        }

        $listRows = $this->request->param('numPerPage') ? 20 : Config::get("paginate.list_rows");

        $list = Db::name('order_refund')
            ->alias('or')
            ->where($map)
            ->order('id', 'desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $new_list = $list->toArray()['data'];
        foreach ($new_list as $k => $v){
            $order = Db::name('order')->where('id',$v['oid'])->field('id,booking_people_name,booking_people_phone')->find();
            $new_list[$k]['booking_people_name'] = $order['booking_people_name'];
            $new_list[$k]['booking_people_phone'] = $order['booking_people_phone'];
        }
        $refund_type = array(
            array('name' => '全额退款','value' => 1),
            array('name' => '部分退款(取消行程)','value' => 2),
            array('name' => '部分退款(继续行程)','value' => 3),
            array('name' => '不退款','value' => 4),
        );
        // 模板赋值显示
        $this->view->assign('searchCondition', $searchData);
        $this->view->assign('refund_type', $refund_type);
        $this->view->assign('list', $new_list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 导出订单电子表格
     * @return mixed
     */
    public function get_excel(Request $request)
    {
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l+65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j].$letter[$k];
            }
        }
        $tableHeader = ['订单号','预订人姓名','预订人电话','退款类型','退款金额','退款时间','退款原因','退款状态','退款渠道'];
        $li_length = count($letter);//设置单元格的宽度
        for ($li=0;$li<$li_length;$li++){
            switch ($letter[$li]){
                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(50);break;
                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);break;
                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(30);break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++){
            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
        }
        if ($data['id']) {
            $id = implode($data['id'], ',');
            $map['or.id'] = ['in', $id];
        }

        //查询要填充表格数据
        $list = Db::name('order_refund')
            ->alias('or')
            ->join('order o','or.oid=o.id','left')
            ->where($map)
            ->order('or.id','desc')
            ->field('or.oid,o.booking_people_name,o.booking_people_phone,or.refund_type,or.refund_money,or.create_time,or.refund_reason,or.refund_status,or.refund_channels')
            ->select();
        //字段转换
        foreach ($list as $lk=>$lv) {
            switch ($lv['refund_type']){
                case '1':
                    $list[$lk]['refund_type'] = '全额退款';break;
                case '2':
                    $list[$lk]['refund_type'] = '部分退款(取消行程)';break;
                case '3':
                    $list[$lk]['refund_type'] = '部分退款(继续行程)';break;
                case '4':
                    $list[$lk]['refund_type'] = '不退款';break;
            }
            switch ($lv['refund_status']){
                case 'check':
                    $list[$lk]['refund_status'] = '审核中';break;
                case 'refunding':
                    $list[$lk]['refund_status'] = '退款中';break;
                case 'refunded':
                    $list[$lk]['refund_status'] = '已退款';break;
                case 'rejected':
                    $list[$lk]['refund_status'] = '拒绝退款';break;
            }
            if(empty($lists[$lk]['refund_status'])){
                $list[$lk]['refund_status'] = '不退款';
            }
            $list[$lk]['create_time'] = date('Y-m-d H:i',$list[$lk]['create_time']);
        }

        //定义table键
        if (!empty($list)){
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk=>$tv){
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++){
                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis',time())."订单管理-退款记录数据.xls";
        $fileName = iconv('utf-8','gb2312',$fileName);
        ob_end_clean();
        if ($request->isGet()){
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename='.$fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        }else{
            // 保存文件到服务器上
            $path = ROOT_PATH."public/excel";
            // 判断文件是否存在
            if (!file_exists($path)){
                mkdir($path,0777,true);
            }
            $fileName = iconv('gb2312','utf-8',$fileName);
            $file = $path."/{$fileName}";
            $writer->save($file);
            $url =$request->domain()."/excel/{$fileName}";
            return ajax_return_adv($url,'','','','','',5);
        }
    }

    /**
     * 删除退款记录
     * @return mixed
     */
    public function delete(){
        $id = input('id');
        if(!$id){
            return ajax_return_adv_error('缺少参数，无法删除');
        }
        $res = Db::name('order_refund')->where('id',$id)->delete();
        if($res){
            return ajax_return_adv('删除成功');
        }else{
            return ajax_return_adv_error('删除失败');
        }
    }

}
